<template>
  <el-form class="form-content" ref="formRef" :model="formData" :disabled="disabled" :label-width="props.labelWidth" :label-position="props.labelPosition">
    <el-form-item v-for="(field,index) in newFields" :key="field.id" :label="field.label" :prop="field.required == 'true' ? field.name : ''" 
      :rules="field.required == 'true' ? [{ required: true, message: `请输入${field.label}`, trigger: 'blur' }] : []" :style="{ width: field.width ? field.width + '%' : '100%' }">
      <template v-if="field.type === 'classify'">
        <el-radio-group v-model="field.value">
          <el-radio v-for="option in field.options" :key="option.value" :label="option.value">
            <span class="radio-label">{{option.label}}</span>

          </el-radio>
        </el-radio-group>
      </template>
      <template v-if="field.type === 'input'">
        <el-input v-model="field.value" placeholder="请输入" :maxlength="field.openRestrict == 'true' ? field.maxLength :''" :show-word-limit="field.openRestrict" :class="{'field-title': index === 0}"/>
      </template>
      <template v-else-if="field.type === 'textarea' && index == 1 && field.value && field.value != ''">
        <div v-html="field.value" class="field-html"></div>
      </template>
      <template v-else-if="field.type === 'textarea'">
        <el-input v-model="field.value" type="textarea" placeholder="请输入" rows="4" />
      </template>
      <template v-else-if="field.type === 'numberInput'">
        <el-input-number v-model="field.value" :min="1" :max="field.maxNumber" :precision="field.precision"/>
      </template>
      <template v-else-if="field.type === 'select'">
        <el-select v-model="field.value" placeholder="请选择">
          <el-option v-for="option in field.options" :key="option.value" :label="option.label" :value="option.value" />
        </el-select>
      </template>
      <template v-else-if="field.type === 'multiSelect'">
        <el-select v-model="field.value" multiple placeholder="请选择">
          <el-option v-for="option in field.options" :key="option.value" :label="option.label" :value="option.value" />
        </el-select>
      </template>
      <template v-else-if="field.type === 'date'">
        <el-date-picker v-model="field.value" placeholder="请选择日期" />
      </template>
      <template v-else-if="field.type === 'upload'">
        <div class="but-list">
          <el-upload :action="uploadAction" :before-upload="beforeUpload" :on-success="res => handleUploadSuccess(res, field.name)">
            <el-button type="primary">点击上传</el-button>
          </el-upload>
          <button class="show-file" @click="showFile(field)" type="button" v-if="field.value">内容预览</button>
          <p class="file-name">{{field.fileName}}</p>
        </div>
      </template>
      <p class="tips">{{ field.description }}</p>
    </el-form-item>
  </el-form>
  <!-- 预览内容对话框 -->
  <el-dialog v-model="previewVisible" title="文件预览" width="1000px" class="preview-dialog">
    <el-scrollbar height="540px">
      <video v-if="previewInfo.fileType == 'video/mp4'" id="video-media" :src="previewInfo.value" controls autoplay ></video>
      <!-- <video
        v-if="previewInfo.fileType == 'video/mp4'"
        :src="previewInfo.value"
      ></video> -->
      <iframe
        v-if="previewInfo.fileType === 'application/pdf'"
        :src="previewInfo.value"
        width="100%"
        height="600px"
        frameborder="0"
      >
        <p>您的浏览器不支持预览此文档。</p>
      </iframe>
      <vue-office-docx v-if="previewInfo.fileType == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'" 
        :src="previewInfo.value" />
    </el-scrollbar>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="previewVisible = false">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref,  defineProps, defineExpose, watch } from 'vue'
import VueOfficeDocx from '@vue-office/docx'
import '@vue-office/docx/lib/index.css'
// import { videoPlay } from 'vue3-video-play'
// import 'vue3-video-play/dist/style.css'

const props = defineProps({
  fields: {
    type: Array,
    default: () => []
  },
  modelValue: {
    type: Object,
    default: () => ({})
  },
  disabled: {
    type: Boolean,
    default: false
  },
  uploadAction: {
    type: String,
    default: ''
  },
  labelWidth: {
    type: String,
    default: ''
  },
  labelPosition: {
    type: String,
    default: 'right'
  }
})
const newFields = ref([...props.fields]);
//去除富文本标签
// const stripHtmlTags = (html) => {
//   const tempDiv = document.createElement("div");
//   tempDiv.innerHTML = html;
//   return tempDiv.textContent || tempDiv.innerText || "";
// }
// const changeField = () => {
//   newFields.value.forEach((field,index) => {
//     if(field.type && field.type === "textarea" && index == 1 && field.value != ""){
//       field.value = stripHtmlTags(field.value);
//     }
//   });
// }

modifyOption(newFields.value)

watch(() => props.fields, (newOptions) => {
  newFields.value = [...newOptions];
  // changeField();
  modifyOption(newFields.value)
}, { deep: true });

function modifyOption(data) {
  data.forEach(item => {
    try {
      const result = JSON.parse(item.options);
      item.options = result
    } catch (e) {
      return item
    }
  });
  // console.log("newFields.value",newFields.value);
  
}

const formRef = ref(null)
const formData = ref({})

// 初始化表单数据
watch(
  () => props.modelValue,
  newVal => {
    formData.value = { ...newVal }
  },
  { immediate: true }
)

// 上传相关方法
const beforeUpload = () => {
  // 在这里添加文件验证逻辑
  return true
}

const handleUploadSuccess = (response, fieldName) => {
  formData.value[fieldName] = response.url
}

// 表单验证方法
const validate = async () => {
  if (!formRef.value) return false
  return await formRef.value.validate()
}

// 重置表单
const resetFields = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 获取表单数据
const getFormData = () => {
  return formData.value
}

//文件预览
const previewVisible = ref(false)
const previewInfo = ref({})
const showFile = (item) => {
  console.log("item",item);
  previewInfo.value = item;
  previewVisible.value = true;
}

//视频播放配置
// const videoOptions = reactive({
//   width: '100%',
//   height: '100%',
//   color: '#409eff', //主题色
//   title: '测试视频播放', //视频名称
//   webFullScreen: false, //网页全屏
//   speed: true, //是否支持快进快退
//   muted: false, //静音
//   autoPlay: true, //自动播放
//   loop: false, //循环播放
//   mirror: false, //镜像画面
//   fluid: true,
//   aspectRatio: '16:9',
//   control: true, //是否显示控制器
//   volume: 0.5, //默认音量0-1
//   notSupportedMessage: '此视频暂无法播放，请稍后再试',
//   type: "mp4",
//   poster: '', //封面
//   speedRate: [1.0, 1.25, 1.5, 2.0], // 可选的播放速度
//   qualityLevels: ['720p', '1080p', '320p'],
//   controlBtns: [
//     'audioTrack', //音轨切换按钮
//     'quality', //视频质量切换按钮
//     'speedRate', //速率切换按钮
//     'volume', //音量
//     'pip', //画中画按钮
//     'fullScreen' //全屏按钮
//   ]
// })

defineExpose({
  validate,
  resetFields,
  getFormData
})
</script>
<style scoped lang="scss">
  .radio-label{
    margin-right: 10px;
  }
  .form-content{
    display: flex;
    flex-wrap: wrap;
  }
  .field-html {
    background: #f5f7fa;
    /* display: inline-flex; */
    flex-grow: 1;
    cursor: not-allowed;
    padding: 11px;
    box-sizing: border-box;
    background-color: var(--el-disabled-bg-color);
    box-shadow: 0 0 0 1px var(--el-disabled-border-color) inset;
    background-image: none;
    border-radius: var(--el-input-border-radius, var(--el-border-radius-base));
    transition: var(--el-transition-box-shadow);
    max-width: 100%;
    min-height: 32px;
    ::v-deep img{
      display: block;
      max-width: 90%;
      margin: 0 auto !important;
      height: auto;
    }
  }
  .field-html ::v-deep *{
    font-size: 16px !important;
    background: none !important;
  }
  .tips{
    font-size: 12px;
    color: #777;
    line-height: 2;
  }
  ::v-deep .el-form-item__content{
    align-items: start;
    margin-right: 10px;
    display: block;
  }
  .el-input{
    height: max-content;
  }
  .but-list{
    display: flex;
    /* align-items: center; */
    .show-file{
      background: white;
      color: $mainColor;
      border-radius: 4px;
      height: 32px;
      border: 1px solid $borderColor;
      margin-left: 10px;
      &:hover {
        background: var(--el-color-primary-light-3);
        color: white;
      }
    }
  }
  .preview-dialog{
    #video-media{
      width: 100%;
    }
    
  }
  .file-name {
    position: absolute;
    left: 0;
    bottom: -15px;
    font-size: 12px;
    line-height: 1.8;
  }
</style>
